package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Ad;
import com.ywgt.service.AdService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin/ad")
@ApiModel("广告管理")
public class AdController {

    @Autowired
    AdService adService;

    /**
     *  page: 1,
     *         limit: 20,
     *         name: undefined,
     *         content: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getAds(String name, String content, @RequestParam(required = false,defaultValue = "add_time") String sort,
                         @RequestParam(required = false,defaultValue = "desc") String order,
                         @RequestParam(required = false,defaultValue = "1") int page,
                         @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Ad> ads=adService.getAds(name,content,page,limit,sort,order);
        List<Ad> items = ads.getResult();
        long total = ads.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Ad ad){
        if(adService.removeById(ad.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Ad ad){
        if(adService.updateById(ad)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/create")
    public Object create(@RequestBody Ad ad){
        if(adService.save(ad)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
